export default class Indexdb {
    constructor(id) {
        this.id = id
        //打开数据库连接,单个文件为一个数据库故id为数据名
        this.request = window.indexedDB.open(id, '1.0');
    }
    openDatabase(callBack) {
        this.request.onupgradeneeded = function (event) {
            //创建表
            event.target.result.createObjectStore('fileData', { keyPath: 'md5' })
        }
        this.request.onsuccess = function (event) {
            callBack(event.target.result)
        }
        this.request.onerror = function (event) {
            console.log('数据库打开报错');
        };
    }
    addObject(data) {
        //碎片md5为数据表主键，data为碎片内容
        this.openDatabase((db) => {
            db.transaction(['fileData'], 'readwrite').objectStore('fileData').add(data);
        })
    }
    getObject(md5) {
        return new Promise((resolve, reject) => {

            this.openDatabase((db) => {
                var transaction = db.transaction(['fileData']);
                var objectStore = transaction.objectStore('fileData');
                var request = objectStore.get(md5);
                request.onerror = function (event) {
                    resolve(false);
                };

                request.onsuccess = function (event) {
                    if (request.result) {
                        resolve(request.result);
                    } else {
                        resolve(false);
                    }
                };
            })
        })
    }
    removeObject() {
        window.indexedDB.deleteDatabase(this.id);
    }

}